package com.tfj.comm.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.tfj.R;
import com.tfj.comm.activity.HomePageActivity;
import com.tfj.utils.ActivityManagerUtils;
import com.tfj.utils.AuthPreferences;
import com.tfj.utils.SysUtils;

import java.util.Date;
import java.util.List;


/**
 * Created by mac on 2018/11/27.
 */

public class EmService extends Service {
    private static final String TAG = "EmService";
    public static final String EM_ACTION = "EM_ACTION";
    private static BroadcastReceiver connectionReceiver;
    private static Context context = null;
    private boolean ifinterrupt = false;
    private static final String PUSH_CHANNEL_ID = "PUSH_NOTIFY_ID";
    private static final String PUSH_CHANNEL_NAME = "PUSH_NOTIFY_NAME";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        context = getApplicationContext();
        if (connectionReceiver == null) {
            connectionReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                    if (networkInfo == null || !networkInfo.isAvailable()) {
                        Toast.makeText(getApplicationContext(), "网络已断开，请重新连接", Toast.LENGTH_SHORT).show();
                        ifinterrupt = true;
                    } else {
                        if (ifinterrupt) {
                            Toast.makeText(getApplicationContext(), "网络已连接", Toast.LENGTH_SHORT).show();
                            ifinterrupt = false;
                        }
                        //这边注册一个全局监听
                        registerEmListener();

                    }

                }
            };
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(connectionReceiver, intentFilter);

        }
        return super.onStartCommand(intent, flags, startId);
    }

    public static void registerEmListener() {
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());
    }

    //实现ConnectionListener接口
    private static class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            Message message = new Message();
            message.arg1 = error;
            handler_logstate.sendMessage(message);
//            runOnUiThread(new Runnable() {
//
//                @Override
//                public void run() {
//                    if (error == EMError.USER_REMOVED) {
//                        // 显示帐号已经被移除
//                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
//                        // 显示帐号在其他设备登录
//                    } else {
//                        if (NetUtils.hasNetwork(MainActivity.this))
//                        //连接不到聊天服务器
//                else
//                        //当前网络不可用，请检查网络设置
//                    }
//                }
//            });
        }
    }

    public static Handler handler_logstate = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int error = msg.arg1;
            if (error == EMError.USER_REMOVED) {
                // 显示帐号已经被移除
                Toast.makeText(context, "该帐号已经被移除", Toast.LENGTH_SHORT).show();
            } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                // 显示帐号在其他设备登录
                AuthPreferences.saveUserInfo("");
                AuthPreferences.saveUserToken("");
                AuthPreferences.saveShop("");
                ActivityManagerUtils.getInstance().finishAllActivity();
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                intent.setClass(context, HomePageActivity.class);
                context.startActivity(intent);
                Toast.makeText(context, "该帐号在其他设备登录", Toast.LENGTH_SHORT).show();
            }
        }
    };

    public static void removeEmListener() {
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
    }

    static EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //收到消息
            Log.i(TAG, "service接收到的消息--->" + JSONObject.toJSONString(messages));
            EMMessage emMessage = messages.get(0);
            EMClient.getInstance().chatManager().importMessages(messages);
            String jsonString = JSONObject.toJSONString(emMessage);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            //如果在后台运行的话则删除所有在栈里的活动
//            if (SysUtils.isBackground(context)) {
//                Log.i(TAG, "在后台");
//                ActivityManagerUtils.getInstance().finishAllActivity();
//            }
            NotificationManager mNotifyMgr =
                    (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
            Intent mainIntent = new Intent(context, HomePageActivity.class);
            mainIntent.putExtra("lauchmode", "radar");
            PendingIntent mainPendingIntent = PendingIntent.getActivity(context, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            //创建 Notification.Builder 对象
            Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            //Uri sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.leida);
            long[] pattern = {0, 100, 1000};
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(PUSH_CHANNEL_ID, PUSH_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                if (mNotifyMgr != null) {
                    mNotifyMgr.createNotificationChannel(channel);
                }
            }
            Notification notification = null;
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    //点击通知后自动清除
                    .setSound(sound)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .setDefaults(0)
                    .setTicker("悬浮通知")
                    .setVibrate(pattern)
                    .setAutoCancel(true)
                    .setChannelId(PUSH_CHANNEL_ID)
                    .setContentTitle(emMessage.getFrom())
                    .setContentText(jsonObject.getJSONObject("body").getString("message"))
                    .setContentIntent(mainPendingIntent);
            notification = builder.build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            //发送通知
            if (SysUtils.isNotificationEnabled(context)) {
                if (mNotifyMgr != null) {
                    mNotifyMgr.notify((int) (new Date().getTime()), notification);
                }
                Log.i(TAG, "有权限");
            } else {
                // TODO Auto-generated method stub
                // 6.0以上系统才可以判断权限
                Toast.makeText(context, "未设置通知权限", Toast.LENGTH_SHORT).show();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                    // 进入设置系统应用权限界面
                    Intent intent = new Intent(Settings.ACTION_SETTINGS);
                    context.startActivity(intent);
                    return;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                    // 进入设置系统应用权限界面
                    Intent intent = new Intent(Settings.ACTION_SETTINGS);
                    context.startActivity(intent);
                    return;
                }
                return;
            }
            String message = JSONObject.toJSONString(emMessage);
            Intent intent = new Intent();
            intent.setAction(EmService.EM_ACTION);
            intent.putExtra("message", message);
            //context.sendBroadcast(intent);
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            Log.i(TAG, "收到透传消息-->" + JSONObject.toJSONString(messages));
            //收到透传消息
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //消息被撤回
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (connectionReceiver != null) {
            Log.i(TAG, "解除了服务");
            unregisterReceiver(connectionReceiver);
            removeEmListener();
        }
    }
}
